import random

class Minesweeper:
    def __init__(self, width=8, height=8, mines_count=10):
        self.width = width
        self.height = height
        self.mines_count = mines_count
        self.board = [] # 地雷布局 (-1为雷)
        self.revealed = [] # 是否已揭开
        self.game_over = False
        self.init_game()

    def init_game(self):
        # 初始化二维列表
        self.board = [[0 for _ in range(self.width)] for _ in range(self.height)]
        self.revealed = [[False for _ in range(self.width)] for _ in range(self.height)]
        
        # 随机布置地雷
        mines_planted = 0
        while mines_planted < self.mines_count:
            x = random.randint(0, self.width - 1)
            y = random.randint(0, self.height - 1)
            if self.board[y][x] != -1:
                self.board[y][x] = -1
                mines_planted += 1
                # 更新周围格子的数字
                for dy in [-1, 0, 1]:
                    for dx in [-1, 0, 1]:
                        ny, nx = y + dy, x + dx
                        if (0 <= ny < self.height and 0 <= nx < self.width and self.board[ny][nx] != -1):
                            self.board[ny][nx] += 1

    def print_board(self, show_all=False):
        """打印游戏棋盘"""
        print('  ' + ' '.join(str(i) for i in range(self.width)))
        for y in range(self.height):
            row = []
            for x in range(self.width):
                if not self.revealed[y][x] and not show_all:
                    row.append('?')
                elif self.board[y][x] == -1:
                    row.append('*') # 地雷
                elif self.board[y][x] == 0:
                    row.append(' ') # 空白
                else:
                    row.append(str(self.board[y][x])) # 数字
            print(f'{y} ' + ' '.join(row))

    def reveal(self, x, y):
        """揭开一个格子"""
        if not (0 <= x < self.width and 0 <= y < self.height) or self.revealed[y][x]:
            return False

        self.revealed[y][x] = True

        if self.board[y][x] == -1:
            self.game_over = True
            return True # 踩到雷了

        # 如果揭开的是空白格，自动递归揭开周围的空白格
        if self.board[y][x] == 0:
            for dy in [-1, 0, 1]:
                for dx in [-1, 0, 1]:
                    self.reveal(x + dx, y + dy)
        return True

# 游戏主循环
if __name__ == "__main__":
    game = Minesweeper()
    
    while not game.game_over:
        game.print_board()
        try:
            x = int(input("请输入列号 (x): "))
            y = int(input("请输入行号 (y): "))
            print("-" * 20)
            if not game.reveal(x, y):
                print("无效的输入或该格子已揭开，请重新选择。")
            if game.game_over:
                print("很遗憾，你踩到地雷了！游戏结束。")
                game.print_board(show_all=True) # 展示全部地雷
        except ValueError:
            print("请输入有效的数字！")
        except KeyboardInterrupt:
            print("\n游戏退出。")
            break